package com.cartagena.financo.util;

import java.util.Calendar;
import java.util.Date;

public final class DateUtil {

    public static Date getDefaultDayBegin() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -30);
        return calendar.getTime();
    }

    public static Date getDefaultDayEnd() {
        return Calendar.getInstance().getTime();
    }
    
    public static Date getDefaultMonthBegin() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -3);
        return calendar.getTime();
    }
    
    public static Date getDefaultMonthEnd() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        return calendar.getTime();
    }
    
    public static int monthsBetween(Date end, Date begin) {
        return monthsBetween(end, begin, true);
    }
    
    public static int monthsBetween(Date end, Date begin, boolean inclusive) {
        Calendar cal = Calendar.getInstance();

        cal.setTime(end);
        int endMonth = cal.get(Calendar.MONTH) + 1;
        int endYear = cal.get(Calendar.YEAR);
        
        cal.setTime(begin);
        int beginMonth = cal.get(Calendar.MONTH) + 1;
        int beginYear = cal.get(Calendar.YEAR);

        int diff = ((endYear - beginYear) * (cal.getMaximum(Calendar.MONTH) + 1)) + (endMonth - beginMonth);
        
        return inclusive ? diff + 1 : diff - 1;
    }
    
    public static Date getMonthFirstDay(Calendar calendar) {
        int minDay = calendar.getMinimum(Calendar.DAY_OF_MONTH);
        
        Calendar monthBegin = Calendar.getInstance();
        monthBegin.setTimeInMillis(calendar.getTimeInMillis());
        monthBegin.set(Calendar.DAY_OF_MONTH, minDay);

        return monthBegin.getTime();
    }
    
    public static Date getMonthLastDay(Calendar calendar) {
        int maxDay = calendar.getMaximum(Calendar.DAY_OF_MONTH);    
        
        Calendar monthEnd = Calendar.getInstance();            
        monthEnd.setTimeInMillis(calendar.getTimeInMillis());
        monthEnd.set(Calendar.DAY_OF_MONTH, maxDay);

        return monthEnd.getTime();
    }
}
